<template>
  <div>
    <!-- 添加角色 -->
    <el-button type="primary" @click="dialogFormVisible1 = true"
      style="margin-left:-1152px"
      >添加角色</el-button
    >
    <div>
      <!-- 角色列表 -->
      <el-table :data="Roleslist.list" style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <!-- <template > -->
            <!-- i1===0    一级权限 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdtop', i1 === 0 ? 'bdbottom' : '', 'vcenter']"
            >
              <el-col :span="5">
                <el-tag
                  size="large"
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <el-icon>
                  <CaretRight />
                </el-icon>
              </el-col>

              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      size="large"
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <!-- 箭头 -->
                    <el-icon>
                      <CaretRight />
                    </el-icon>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      size="large"
                      type="warning"
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="角色描述" prop="roleDesc" />
        <el-table-column label="操作" prop="">
          <template #default="scope">
            <el-button
              type="primary"
              @click="(dialogFormVisible = true), setcompile(scope.row)"
              :icon="Edit"
              >编辑</el-button
            >
            <el-button type="danger" :icon="Delete" @click="open(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              :icon="Star"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogFormVisible" title="编辑角色">
        <el-form :model="form">
          <el-form-item label="角色名称">
            <el-input v-model="form.roleName" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.roleDesc" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="(dialogFormVisible = false), UserRolesets()"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 添加对话框 -->
      <el-dialog v-model="dialogFormVisible1" title="添加角色">
        <el-form :model="form1">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="form1.roleName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色描述" :label-width="formLabelWidth">
            <el-input v-model="form1.roleDesc" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible1 = false">取消</el-button>
            <el-button
              type="primary"
              @click="(dialogFormVisible1 = false), AddRolesets()"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 分配权限的对话框 -->
      <el-dialog
        title="分配权限"
        v-model="SetRightDialogVisible"
        width="50%"
        @close="SetRightDialogVisibleClosed"
      >
        <!-- 树形控件 -->
        <!-- :props="treeProps" 标题 279行 -->
        <!-- show-checkbox 多选框 -->
        <!-- node-key= 唯一标识  记录是否被选中 -->
        <!-- :default-expand-all="true" 默认展开所有的字树 -->
        <!-- :default-checked-keys="defKeys" 默认选中的列表 -->
        <el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="defKeys"
          ref="treeRef"
        ></el-tree>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="SetRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
import {
  UserRoleList,
  UserRoleset,
  AddRoleset,
  deleteleset,
  putRightslist,
  postRoleRights,
  deleteRightRole,
} from "../tools/ajax";
import {
  Edit,
  Delete,
  Star,
  ArrowRight,
  Setting,
  EditPen,
  CaretRight,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 角色列表
const Roleslist = reactive({
  list: [],
});
// 添加角色信息
const form1 = reactive({
  roleName: "",
  roleDesc: "",
});
// 添加角色
function AddRolesets() {
  AddRoleset({ roleName: form1.roleName, roleDesc: form1.roleDesc }).then(
    (res) => {
      console.log(res);
      if (res.meta.status == 201) {
        ElMessage.success(res.meta.msg);
        UserRoleList1();
      } else {
        ElMessage.error(res.meta.msg);
      }
    }
  );
}
// 编辑信息
const form = reactive({
  roleName: "",
  roleDesc: "",
  id: "",
});
// 修改编辑信息
function setcompile(item) {
  console.log(item);
  form.roleName = item.roleName;
  form.roleDesc = item.roleDesc;
  form.id = item.id;
}
// 编辑角色信息
function UserRolesets() {
  UserRoleset({
    id: form.id,
    roleName: form.roleName,
    roleDesc: form.roleDesc,
  }).then((res) => {
    console.log(res);
    if (res.meta.status == 200) {
      ElMessage.success(res.meta.msg);
      UserRoleList1();
    } else {
      ElMessage.error(res.meta.msg);
    }
  });
}
// 删除角色
function deletcompile(id) {
  deleteleset({ id: id }).then((res) => {
    console.log(res);
    UserRoleList1();
  });
}
// 删除弹窗
const open = (id) => {
  ElMessageBox.confirm("此操作将永久删除该用户, 是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      deletcompile(id);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
const dialogFormVisible = ref(false);
const dialogFormVisible1 = ref(false);
// 获取角色列表
function UserRoleList1() {
  UserRoleList().then((res) => {
    console.log(res);
    Roleslist.list = res.data;
  });
}
UserRoleList1();

// 删除角色权限
function removeRightById(roles, rightId) {
  ElMessageBox.confirm("此操作将永久删除该用户, 是否继续?", "删除权限", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      deleteRightRole({
        roleId: roles.id,
        rightId,
      }).then((res) => {
        console.log(res);
        roles.children = res.data;
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
}

// #region 6,分配权限
const SetRightDialogVisible = ref(false); // 展示分配权限对话框
const treeRef = ref(null); // 展示权限的树形结构表单
const rightsList = reactive([]); // 权限列表
const treeProps = reactive({
  // 树形控件的绑定对象
  children: "children",
  label: "authName",
});
// ---
const defKeys = reactive([]); // 树形控件 -> 默认选中的节点id值数组
var currentRoleId; // 记录当前设置的角色id
putRightslist({ type: "tree" }).then((res) => {
  // 请求所有权限列表
  if (res.meta.status !== 200) {
    return ElMessage.error(res.meta.msg);
  }
  // 获取到的权限数据保存
  rightsList.push(...res.data);
  // console.log(rightsList)
});
// 显示权限分配对话框
async function showSetRightDialog(roles) {
  // 递归获取所有选中三级节点
  getLeafKeys(roles);
  SetRightDialogVisible.value = true;
  currentRoleId = roles.id; // 记录当前角色id
}
// 递归的形式,获取角色下所有的三级权限的id,并保存到 defKeys数组中
function getLeafKeys(node) {
  // 递归的写法如果当前node没有children属性则是三级节点,选中
  // if (!node.children) {
  //     return defKeys.push(node.id)
  // }
  // node.children.forEach(item => getLeafKeys(item))

  // 不用递归的写法: 嵌套循环三次,找到所有三级权限,选中
  node.children.forEach((item1) => {
    item1.children.forEach((item2) => {
      item2.children.forEach((item3) => {
        defKeys.push(item3.id);
      });
    });
  });
  // console.log(defKeys,treeRef.value);
  // defKeys 更新后,树形列表的选中状态不会自动更新, 要调用函数更新 (没展示前是null)
  treeRef.value && treeRef.value.setCheckedKeys(defKeys);
}
// 确认保存用户权限分配结果
async function allotRights() {
  // 获取表单中的选中节点和半选中节点, 放入数组
  // console.log(treeRef.value);
  const keys = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ];
  // console.log(keys);
  // 把所有选中的id拼接成字符串
  const idStr = keys.join(",");
  // console.log(idStr);
  // 分配权限
  var res = await postRoleRights({
    roleId: currentRoleId,
    rids: idStr,
  });
  // console.log(res);
  if (res.meta.status !== 200) {
    return ElMessage.error("分配权限失败!");
  }
  ElMessage.success("分配权限成功!");
  UserRoleList1();
  SetRightDialogVisible.value = false;
}
// 关闭分配权限对话框时的回调
function SetRightDialogVisibleClosed() {
  // 清空 defkeys 数组  避免累积
  defKeys.splice(0);
}
</script>
<style scoped lang="less">
.cont {
  display: flex;
  justify-content: space-between;
  text-align: left;
  color: gray;
  line-height: 50px;
  .cont-text1 {
    width: 50px;
    height: 50px;
    
  }
  .cont-text2 {
    width: 400px;
    height: 50px;
  }
}
.el-col {
  text-align: left;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

.el-input {
  width: 80%;
}
</style>